package cn.jbolt.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
public class ReflectiveApiCall {

    private static final Logger logger = LoggerFactory.getLogger(ReflectiveApiCall.class);

    /**
     * 反射调取api
     * @param fullPathClassName 全限定类名,例如:com.jbolt.ai.demo.controller.FunctionCallTestController
     * @param methodName 方法名 inviteJob
     * @param args 参数
     * @return
     */
    public static Result callApi(String fullPathClassName, String methodName, Object... args) {
        try {
            // 获取Controller类对象
            Class<?> controllerClass = Class.forName(fullPathClassName);
            Object controllerInstance = SpringContextUtil.getApplicationContext().getBean(controllerClass);

            // 解析参数类型数组，用于获取对应的方法对象
            Class<?>[] parameterTypes = getParameterTypes(args);

            // 获取要调用的方法对象
            Method method = controllerClass.getMethod(methodName, parameterTypes);
            Result result = (Result) method.invoke(controllerInstance, args);
            logger.info("反射调用方法成功：{}" , result);
            // 调用方法
            return result;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("反射调用方法失败：{}" , e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    private static Class<?>[] getParameterTypes(Object... args) {
        List<Class<?>> typeList = new ArrayList<>();
        if (args != null && args.length > 0) {
            for (Object arg : args) {
                typeList.add(arg.getClass());
            }
        }
        return typeList.toArray(new Class<?>[0]);
    }

}
